package com.ai.learning.framework.core.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.ai.learning.framework.core.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 融合精细化异常分类处理，与Django后端保持响应格式一致
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 1. 业务异常处理
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常 [{}]: {}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 2. 参数校验异常处理（Bean Validation）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e, HttpServletRequest request) {
        
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("参数校验失败 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.VALIDATION_FAILED.getCode(), message);
    }

    /**
     * 3. 约束违规异常处理（单个参数校验）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> handleConstraintViolationException(
            ConstraintViolationException e, HttpServletRequest request) {
        
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("参数约束违规 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.VALIDATION_FAILED.getCode(), message);
    }

    /**
     * 4. 缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Void> handleMissingServletRequestParameterException(
            MissingServletRequestParameterException e, HttpServletRequest request) {
        
        String message = String.format("缺少必要参数: %s", e.getParameterName());
        log.warn("缺少请求参数 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.MISSING_PARAMETER.getCode(), message);
    }

    /**
     * 5. 参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<Void> handleMethodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        
        String message = String.format("参数 %s 类型错误，期望 %s", 
                e.getName(), e.getRequiredType().getSimpleName());
        log.warn("参数类型不匹配 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.INVALID_PARAMETER.getCode(), message);
    }

    /**
     * 6. HTTP请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Void> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        
        String message = String.format("不支持的请求方法: %s", e.getMethod());
        log.warn("HTTP方法不支持 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.METHOD_NOT_ALLOWED.getCode(), message);
    }

    /**
     * 7. JSON解析异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Void> handleHttpMessageNotReadableException(
            HttpMessageNotReadableException e, HttpServletRequest request) {
        
        log.warn("JSON解析失败 [{}]: {}", request.getRequestURI(), e.getMessage());
        return Result.error(ErrorCode.INVALID_PARAMETER.getCode(), "请求体格式错误");
    }

    /**
     * 8. 文件上传参数缺失异常
     */
    @ExceptionHandler(MissingServletRequestPartException.class)
    public Result<Void> handleMissingServletRequestPartException(
            MissingServletRequestPartException e, HttpServletRequest request) {
        
        String message = String.format("缺少文件上传参数: %s", e.getRequestPartName());
        log.warn("文件上传参数缺失 [{}]: {}", request.getRequestURI(), message);
        return Result.error(ErrorCode.MISSING_PARAMETER.getCode(), message);
    }

    /**
     * 9. 运行时异常兜底处理
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常 [{}]", request.getRequestURI(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统处理异常，请稍后重试");
    }

    /**
     * 10. 系统异常兜底处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常 [{}]", request.getRequestURI(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统内部错误");
    }
}